package com.mgy.db.sharding.strategy;

import com.mgy.db.TableRouter;
import org.apache.shardingsphere.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.hint.HintShardingValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 基于hint的分表策略
 *
 * @author mgy
 */
public class TableHintShardingAlgorithm implements HintShardingAlgorithm<TableRouter> {

    @Override
    public Collection<String> doSharding(final Collection<String> availableTargetNames, final HintShardingValue<TableRouter> shardingValue) {
        List<String> shardingList = new ArrayList<>(shardingValue.getValues().size());

        for (TableRouter tableRouter : shardingValue.getValues()) {
            if (tableRouter.getTableSeparator() != null) {
                String actualTable = tableRouter.getLogicTable() + tableRouter.getTableSeparator() + tableRouter.getTableNo();
                if (availableTargetNames.contains(actualTable)) {
                    shardingList.add(actualTable);
                }
            } else {
                for (String separator : TableRouter.DEFAULT_TABLE_SEPARATOR) {
                    String actualTable = tableRouter.getLogicTable() + separator + tableRouter.getTableNo();
                    if (availableTargetNames.contains(actualTable)) {
                        shardingList.add(actualTable);
                        break;
                    }
                }
            }
        }
        if (shardingList.isEmpty()) {
            throw new IllegalArgumentException("分表参数错误");
        }
        return shardingList;
    }

}
